<?php

namespace app\backend\controller;

use app\backend\library\DataController;
use app\backend\validator\AddCategoryValidator;
use app\backend\validator\UpdCategoryValidator;
use app\common\model\ProductCategory;

class Category extends DataController
{
    protected $mdl = ProductCategory::class;

    protected $excludeMainFields = ['is_deleted', 'deleted_at'];

    protected $allowSortFields = [
        "id",
        "aid",
        "status",
        "created_at",
    ];

    protected $allowSearchFields = [
        'id',
        "aid",
        'status',
        'category_name',
        'Manager.username',
        'created_at',
    ];

    protected $relations = [
        'Manager' => [
            'type' => 'join',
            'alias' => 'a',
            'table' => 'abtm_admin_user',
            'on' => 'abtm_product_category.aid = a.id',
            'join_type' => 'left',
            'fields' => ['id', 'username']
        ]
    ];

    protected function applySearch($query, $params)
    {
        parent::applySearch($query, $params);

        $query->where($this->mainFieldAlias('is_deleted'), $this->mdl::NO_DELETED);
    }

    protected function _printDataHook(&$items)
    {
        $url = env('url.frontend_url');

        foreach ($items as $item) {
            if(!empty($item->img_url)) {
                $item->img_url = buildFullUrl($url, 'storage/'. $item->img_url);
            }
        }
    }

    protected function _saveBeforeHook(&$params)
    {
        if(empty($params['id'])) {
            $this->validate($params, AddCategoryValidator::class);
        }else{
            $this->validate($params, UpdCategoryValidator::class);
        }
    }
}